<template>
  <div class="Storebox">
    <!-- 多功能表格组件 -->
    <eveningStar
      :showTableControl="true"
      @addNew="addNew"
      @edit="edit({ item: tableCheckedArr[0] })"
      @deltable="deltable"
      @tabselect="tabselect"
      @refreshData="refreshData"
      :ableEdit="ableEdit"
      :ableDel="ableDel"
      :border="false"
      :showcheckbox="true"
      :tableData="tableData"
      :headData="headData"
      @SizeChange="SizeChange"
      @CurrentChange="CurrentChange"
      :total="total"
      :pagesize="pagesize"
      :currentpage="currentpage"
    >
      <template v-slot:isShow="{ row }">
        <el-tag size="small" v-if="row.isShow">显示</el-tag>
        <el-tag size="small" v-if="!row.isShow" type="info">隐藏</el-tag>
      </template>
      <template v-slot:image="{ row }">
        <div class="imageBox">
          <el-image
            style="width: 100%; height: 100%"
            :src="row.image"
          ></el-image>
        </div>
      </template>
      <template v-slot:operation="{ row }">
        <el-button
          type="primary"
          size="mini"
          @click="edit(row)"
          icon="el-icon-edit"
        ></el-button>
        <el-popconfirm
          @confirm="handleConfirm(row)"
          title="确定删除本条数据吗？"
        >
          <el-button
            slot="reference"
            type="danger"
            size="mini"
            icon="el-icon-delete"
          ></el-button>
        </el-popconfirm>
      </template>
    </eveningStar>
    <!-- 增改弹窗 -->
    <el-dialog
      :title="thistitle + '门店'"
      class="popup"
      :before-close="handleClose"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="门店名称" class="labelItem" prop="name">
          <el-input
            size="small"
            class="fireWidth"
            v-model="form.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="门店简介" class="labelItem" prop="introduction">
          <el-input
            size="small"
            class="fireWidth"
            v-model="form.introduction"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="门店手机" class="labelItem" prop="phone">
          <el-input
            size="small"
            class="fireWidth"
            v-model="form.phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="门店地址" class="labelItem" prop="address">
          <el-input
            size="small"
            class="fireWidth"
            v-model="form.address"
            autocomplete="off"
          ></el-input>
          <el-button
            type="primary"
            size="small"
            @click="SystemStoregetLFn"
            class="getLbtn"
            >获取经纬度</el-button
          >
        </el-form-item>
        <el-form-item
          label="门店logo"
          class="labelItem"
          style="margin: 22px 0 0 10px"
        >
          <ul class="fireWidth flexbox">
            <li class="imgList" v-if="form.image">
              <el-image class="elimg" :src="form.image"> </el-image>
              <div class="iconBg">
                <div class="ibox">
                  <i @click="lookBigimg(form.image)" class="el-icon-view"></i>
                  <i @click="delImg()" class="el-icon-delete"></i>
                </div>
              </div>
            </li>
            <li
              class="addImage"
              v-if="!form.image"
              @click="dialogVisiblePicFn(1)"
            >
              <i class="el-icon-plus"></i>
            </li>
          </ul>
        </el-form-item>
        <el-form-item label="纬度" class="labelItem" prop="latitude">
          <el-input
            :disabled="true"
            size="small"
            class="fireWidth"
            v-model="form.latitude"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="经度" class="labelItem" prop="longitude">
          <el-input
            :disabled="true"
            size="small"
            class="fireWidth"
            v-model="form.longitude"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="核销时效" class="labelItem" prop="validTime">
          <el-date-picker
            v-model="form.validTime"
            type="daterange"
            range-separator="-"
            size="small"
            style="width: 370px"
            @change="validTimeFn"
            format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="营业时间" class="labelItem" prop="dayTime">
          <el-time-picker
            is-range
            v-model="form.dayTime"
            range-separator="-"
            size="small"
            style="width: 370px"
            @change="dayTimeFn"
            format="HH:mm:ss"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
          >
          </el-time-picker>
        </el-form-item>
        <el-form-item
          label="是否显示"
          class="labelItem"
          prop="isShow"
          style="display: flex"
        >
          <el-radio v-model="form.isShow" :label="1">显示</el-radio>
          <el-radio v-model="form.isShow" :label="0">隐藏</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose" type="text" size="small"
          >取 消</el-button
        >
        <el-button type="primary" @click="submitForm('ruleForm')" size="small"
          >确 认</el-button
        >
      </div>
    </el-dialog>
    <el-dialog :visible.sync="imgVisible" class="dialog2">
      <img width="100%" :src="thisimg" />
    </el-dialog>
    <picchoose
      :dialogVisiblePic="dialogVisiblePic"
      ref="dialogVisiblePic"
      @closeDialogpic="closeDialogpic"
      @PicTrue="PicTrue"
      :checkNum="checkNum"
    >
    </picchoose>
  </div>
</template>

<script>
import {
  yxSystemStore,
  SystemStoregetL,
  yxSystemStoreAddorEdit,
  DelyxSystemStore
} from "@/api/StoreList";

import picchoose from "@/components/picchoose.vue";
import moment from "moment";
import eveningStar from "@/components/eveningStar.vue";
export default {
  name: "StoreList",
  components: { eveningStar, picchoose },
  data() {
    return {
      tableCheckedArr: [], //被选中的表格项
      itemIscheck: false, // 右上复选框组中每项的选中状态
      thistitle: "", //弹窗标题
      dialogVisiblePic: false,
      checkNum: 1,
      thisimg: "",
      imgVisible: false,
      dialogFormVisible: false,
      form: {
        name: "",
        introduction: "",
        phone: "",
        address: "",
        image: "",
        latitude: "",
        longitude: "",
        validTime: "",
        dayTime: "",
        isShow: 1,
        // 提交包含
        addTime: null,
        dayTimeArr: [],
        dayTimeEnd: "",
        dayTimeStart: "",
        detailedAddress: "",
        id: "",
        imageArr: [],
        validTimeArr: [],
        validTimeEnd: "",
        validTimeStart: "",
      },
      rules: {
        name: [
          { required: true, message: "门店名称不能为空", trigger: "blur" },
        ],
        introduction: [
          { required: true, message: "简介不能为空", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "省市区不能为空", trigger: "blur" },
        ],
        latitude: [
          { required: true, message: "纬度不能为空", trigger: "change" },
        ],
        longitude: [
          { required: true, message: "经度不能为空", trigger: "change" },
        ],
        isShow: [
          { required: true, message: "经度不能为空", trigger: "change" },
        ],
      },
      lastitem: "",
      ableEdit: false,
      ableDel: false,
      currentpage: 0,
      pagesize: 10,
      total: 0,
      // 表格数据
      tableData: [],
      // 表头数据
      headData: [
        {
          prop: "id",
          label: "id",
          width: 50,
        },
        {
          prop: "name",
          label: "门店名称",
        },
        {
          prop: "phone",
          label: "门店电话",
        },
        {
          prop: "address",
          label: "地址",
          show: true,
        },
        {
          prop: "image",
          label: "门店logo",
          slot: true,
        },
        {
          prop: "validTime",
          label: "核销有效日期",
        },
        {
          prop: "dayTime",
          label: "营业时间",
        },
        {
          prop: "isShow",
          label: "是否显示",
          slot: true,
        },
      ],
    };
  },
  mounted() {
    this.yxSystemStoreFn();
  },
  methods: {
    PicTrue(src) {
      let _self = this;
      this.form.image = src;
      _self.$refs.dialogVisiblePic.dialogVisiblePic = false;
    },
    clearObject(obj) {
      Object.keys(obj).forEach((key) => {
        const value = obj[key];
        if (Array.isArray(value)) {
          obj[key] = [];
        } else {
          obj[key] = "";
        }
      });
    },
    // 日期改变
    validTimeFn(validTimeArr) {
      console.log(validTimeArr);
      this.form.validTimeArr = [];
      this.form.validTimeStart = moment(validTimeArr[0]).valueOf();
      this.form.validTimeEnd = moment(validTimeArr[1]).valueOf();
      this.form.validTimeArr.push(this.form.validTimeStart);
      this.form.validTimeArr.push(this.form.validTimeEnd);
    },
    // 时间改变
    dayTimeFn(dayTimeArr) {
      console.log(dayTimeArr);
      this.form.dayTimeArr = [];
      this.form.dayTimeStart = moment(dayTimeArr[0]).valueOf();
      this.form.dayTimeEnd = moment(dayTimeArr[1]).valueOf();
      this.form.dayTimeArr.push(this.form.dayTimeStart);
      this.form.dayTimeArr.push(this.form.dayTimeEnd);
    },
    // 关闭重置表单
    handleClose() {
      this.$refs.ruleForm.resetFields();
      this.clearObject(this.form);
      this.dialogFormVisible = false;
    },
    // 确认新增或修改
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.image) {
            if (this.form.validTime && this.form.dayTime) {
              this.form.imageArr.push(this.form.image);
              this.form.validTimeArr[0] = moment(
                this.form.validTimeArr[0]
              ).format("yyyy-MM-DD");
              this.form.validTimeArr[1] = moment(
                this.form.validTimeArr[1]
              ).format("yyyy-MM-DD");
              this.form.validTime = this.form.validTimeArr.join(" - ");
              this.form.dayTimeArr[0] = moment(this.form.dayTimeArr[0]).format(
                "HH:mm:ss"
              );
              this.form.dayTimeArr[1] = moment(this.form.dayTimeArr[1]).format(
                "HH:mm:ss"
              );
              this.form.dayTime = this.form.dayTimeArr.join(" - ");
            }
            let data = this.form;
            yxSystemStoreAddorEdit(data)
              .then(() => {
                this.$notify({
                  title: this.form.id ? "修改成功" : "添加成功",
                  type: "success",
                });
                this.$refs.ruleForm.resetFields();
                this.dialogFormVisible = false;
                this.clearObject(this.form);
                this.yxSystemStoreFn();
              })
              .catch((err) => {
                this.$notify({
                  title: err.response.data.message,
                  type: "error",
                });
              });
          } else {
            this.$notify({
              title: "请上传门店logo",
              type: "error",
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 关闭图片弹窗
    closeDialogpic() {
      let _self = this;
      _self.$refs.dialogVisiblePic.dialogVisiblePic = false;
    },
    // 打开图片弹窗
    dialogVisiblePicFn(num) {
      let _self = this;
      _self.checkNum = num;
      _self.$refs.dialogVisiblePic.dialogVisiblePic = true;
    },
    // 查看大图
    lookBigimg(img) {
      if (img) {
        this.thisimg = img;
        this.imgVisible = true;
      }
    },
    // 删除图片
    delImg() {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.form.image = "";
        })
        .catch(() => {});
    },
    // 对象赋值封装
    fillEmptyFields(emptyObj, valObj) {
      for (let key in valObj) {
        if (
          emptyObj.hasOwnProperty(key) &&
          (emptyObj[key] === null ||
            emptyObj[key] === undefined ||
            ((Array.isArray(emptyObj[key]) ||
              typeof emptyObj[key] === "string") &&
              emptyObj[key].length === 0))
        ) {
          emptyObj[key] = valObj[key];
        }
      }
    },
    // 省市区经纬度查询
    SystemStoregetLFn() {
      let data = this.form.address;
      SystemStoregetL(data).then((res) => {
        if (res.status == "1") {
          console.log(res.geocodes[0].location);
          let Larr = res.geocodes[0].location.split(",");
          this.form.address = res.geocodes[0].formatted_address;
          [this.form.longitude, this.form.latitude] = Larr;
        } else {
          this.$notify({
            title: "请输入合法地址",
            type: "error",
          });
        }
      });
    },
    // table选择状态变化
    tabselect(selection) {
      this.tableCheckedArr = selection;
      selection.length == 1 ? (this.ableEdit = true) : (this.ableEdit = false);
      selection.length == 0 ? (this.ableDel = false) : (this.ableDel = true);
    },
    // 刷新按钮
    refreshData() {
      this.yxSystemStoreFn();
    },
    // 删除多选表格
    deltable() {
      let delIdArr = []
        this.tableCheckedArr.forEach(item=>{
          delIdArr.push(item.id)
        })
      this.$confirm(`确认删除选中的${ delIdArr.length }条数据？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        DelyxSystemStore(delIdArr).then(()=>{
          this.yxSystemStoreFn()
          this.$notify({
            title: "操作成功",
            type: "success",
          });
        })
      })
    },
    //删除当前行
    handleConfirm({item}) {
      let arr = [];
      arr.push(item.id);
      DelyxSystemStore(arr).then(()=>{
          this.yxSystemStoreFn()
          this.$notify({
            title: "操作成功",
            type: "success",
          });
      })
    },
    // 新增弹窗
    addNew() {
      this.thistitle = "新增";
      this.form.dayTime = "";
      this.form.isShow = 1;
      this.dialogFormVisible = true;
    },
    // 编辑打开弹窗
    edit({ item }) {
      this.thistitle = "编辑";
      this.form.dayTime = [
        moment(item.dayTimeStart).format("yyyy-MM-DD HH:mm:ss"),
        moment(item.dayTimeEnd).format("yyyy-MM-DD HH:mm:ss"),
      ];
      this.form.validTime = item.validTime.split(" - ");
      console.log(this.form.dayTime);
      this.fillEmptyFields(this.form, item);
      this.dialogFormVisible = true;
    },
    CurrentChange(pegeNum) {
      this.currentpage = pegeNum - 1;
      this.yxSystemStoreFn();
    },
    SizeChange(pageSize) {
      this.pagesize = pageSize;
      this.yxSystemStoreFn();
    },

    // 获取门店数据
    yxSystemStoreFn() {
      let data = {
        pageNum: this.currentpage,
        pageSize: this.pagesize,
      };
      yxSystemStore(data).then((res) => {
        this.tableData = [];
        console.log(res.content);
        this.total = res.totalElements;
        for (let item of res.content) {
          this.tableData.push({
            address: item.address,
            dayTime: item.dayTime,
            dayTimeEnd: item.dayTimeEnd,
            dayTimeStart: item.dayTimeStart,
            detailedAddress: item.detailedAddress,
            id: item.id,
            image: item.image,
            introduction: item.introduction,
            isShow: item.isShow,
            latitude: item.latitude,
            longitude: item.longitude,
            name: item.name,
            phone: item.phone,
            validTime: item.validTime,
            validTimeEnd: item.validTimeEnd,
            validTimeStart: item.validTimeStart,
          });
        }
      });
    },
  },
};
</script>

<style lang="less">
.Storebox {
  .popup {
    .el-dialog {
      .el-form-item__content {
        display: flex;
        align-items: center;
      }
      margin-top: 12vh !important;
      .el-dialog__body {
        max-height: 57vh;
        overflow-y: scroll;
      }
    }
  }
  .dialog2 {
    .el-dialog {
      width: 35% !important;
    }
  }
  .addImage {
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    cursor: pointer;
    line-height: 146px;
    vertical-align: top;
    &:hover {
      border-color: #1890ff;
    }
    i {
      font-size: 28px;
      color: #8c939d;
    }
  }
  .flexbox {
    list-style: none;
    display: flex;
    flex-wrap: wrap;
  }
  .getLbtn {
    margin-left: 66px;
  }
  .el-form-item__label {
    min-width: 68px !important;
  }
  .labelItem {
    font-weight: bold !important;
  }
  .el-form-item {
    margin-bottom: 16px !important;
  }
  .fireWidth {
    width: 370px;
    .imgList {
      height: 150px;
      width: 150px;
      position: relative;
      margin-right: 8px;
      margin-bottom: 8px;
      &:hover .iconBg {
        display: block;
      }
      .iconBg {
        position: absolute;
        top: 0;
        left: 0;
        width: 150px;
        display: none;
        height: 150px;
        border-radius: 6px;
        background-color: rgba(0, 0, 0, 0);
        transition: all 0.3s;
        &:hover {
          background-color: rgba(0, 0, 0, 0.5);
        }
        .ibox {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: space-around;
          align-items: center;
          i {
            font-size: 20px;
            color: #fff;
            cursor: pointer;
          }
        }
      }
      .elimg {
        width: 100%;
        height: 100%;
        border-radius: 5px;
        box-sizing: border-box;
        border: 1px solid #c0ccda;
      }
    }
  }
  .el-popover {
    box-sizing: border-box !important;
  }
  .imageBox {
    border-radius: 50%;
    background: #ccc;
    width: 35px;
    height: 35px;
    img {
      border-radius: 50%;
    }
  }
  .el-checkbox:last-of-type {
    margin-right: 30px;
  }
}
</style>